﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DirectOPCClient.httpsocket
{
    public class HttpSocket
    {
        HttpListener httpListener;
        public void Run()
        {

            httpListener = new HttpListener();
            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            httpListener.Prefixes.Add("http://127.0.0.1:8080/lmj/");

            httpListener.Start();
            new Thread(new ThreadStart(delegate {
                try
                {
                    loop(httpListener);
                }
                catch (Exception ex)
                {
                    //httpListener.Stop();
                    Console.WriteLine(ex.Message);
                }
            })).Start();
        }

        private void loop(object httpListener1)
        {

            HttpListener httpListener = (HttpListener)httpListener1;
            while (true)
            {
                HttpListenerContext context = httpListener.GetContext();

                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(context);

            }

            //httpListener.Close();
        }


        private void ReceiveMessage(object context)
        {
            HttpListenerContext myClientSocket = (HttpListenerContext)context;
            HttpListenerRequest hRequest = myClientSocket.Request;
            HttpListenerResponse hResponse = myClientSocket.Response;


            if (hRequest.HttpMethod == "POST")
            {

                //获取参数
                /*Stream SourceStream = hRequest.InputStream;//获取输入流
                var resultStream = new MemoryStream();
                while (true)
                {
                    int data = SourceStream.ReadByte(); //读取数据
                    resultStream.WriteByte((byte)data);
                    if (data == -1)
                        break;
                }
                resultStream.Position = 0;
                byte[] dataBytes = new byte[resultStream.Length - 1];
                resultStream.Read(dataBytes, 0, dataBytes.Length);*/




                Console.WriteLine("POST:" + hRequest.Url);
                string result = JsonConvert.SerializeObject(MainForm.cache);
                byte[] res = Encoding.UTF8.GetBytes(result);
                hResponse.OutputStream.Write(res, 0, res.Length);
            }
            else if (hRequest.HttpMethod == "GET")
            {

                Console.WriteLine("GET:" + hRequest.Url);
                string result = JsonConvert.SerializeObject(MainForm.cache);
                byte[] res = Encoding.UTF8.GetBytes(result);
                hResponse.OutputStream.Write(res, 0, res.Length);
            }
            hResponse.OutputStream.Close();
        }

    }
}
